package com.ilaisa.laishang.wxapi

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.cherry.androidcode.AppConstant.WX_APP_ID
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/**
 * 专门给微信支付回调的，包名或类名不一致会造成无法回调！！！
 * @author DongMS
 * @since 2020/4/9
 */
//不能改成AppCompatActivity
class WXPayEntryActivity : Activity(), IWXAPIEventHandler {

    private val wxapi by lazy {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例，第三个参数是否检查签名
        WXAPIFactory.createWXAPI(this, WX_APP_ID, true)
    }

    private val wxBroadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                // 将该app注册到微信
                wxapi.registerApp(WX_APP_ID)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        regToWx()
        wxapi.handleIntent(intent, this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        wxapi.handleIntent(intent, this)
    }

    private fun regToWx() {

        // 将应用的appId注册到微信
        wxapi.registerApp(WX_APP_ID)

        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(wxBroadcastReceiver, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    override fun onReq(p0: BaseReq) {

    }

    //app发送消息给微信，处理返回消息的回调
    override fun onResp(res: BaseResp) {
        when (res.type) {
            ConstantsAPI.COMMAND_PAY_BY_WX -> {
                //支付
                handlerPay(res)
            }
            else -> {
                //nothing
            }
        }
    }

    private fun handlerPay(res: BaseResp) {
        when (res.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                Toast.makeText(applicationContext, "用户支付成功", Toast.LENGTH_SHORT).show()
            }
            BaseResp.ErrCode.ERR_COMM -> {
                Log.e("wechat", "微信支付失败原因：${res.errStr}")
                Toast.makeText(applicationContext, "用户支付失败", Toast.LENGTH_SHORT).show()
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                Toast.makeText(applicationContext, "用户取消支付", Toast.LENGTH_SHORT).show()
            }
            else -> {
            }
        }
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(wxBroadcastReceiver)
    }
}
